<template>
  <div class="page-container">
    <div class="container">
    <h1>员工绩效历史</h1>
    <div>
      <el-button type="primary" @click="addPerformanceAll" style="margin-bottom: 20px;">
        为全部人新增绩效记录
      </el-button>
      <el-button type="success" @click="openAddPerformanceByIdDialog" style="margin-bottom: 20px;">
        为指定人新增绩效记录
      </el-button>
    </div>
    <!-- 表格展示 -->
    <el-table :data="performanceRecords" border stripe style="width: 100%">
      <el-table-column prop="id" label="绩效记录ID" width="150" align="center" />
      <el-table-column prop="employeeName" label="员工姓名" width="150" align="center" />
      <el-table-column prop="performanceIndicator" label="绩效指标" align="center" />
      <el-table-column prop="performanceFeedback" label="绩效反馈" align="center" />
      <el-table-column prop="performanceScore" label="绩效得分" width="150" align="center" />
      <el-table-column prop="createdAt" label="创建时间" width="200" align="center">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>

      <!-- 添加操作列，包含修改按钮 -->
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <div class="button-group-vertical">
            <el-button type="primary" @click="editPerformance(scope.row)" >修改绩效记录</el-button>
            <el-button type="success" @click="editSalary(scope.row)" >发放/修改工资</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改绩效记录弹窗 -->
    <el-dialog v-model="dialogVisible" title="修改绩效记录">
      <el-form :model="editData" ref="form" label-width="100px">
        <el-form-item label="绩效记录ID">
          <el-input v-model="editData.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="editData.employeeName" disabled></el-input>
        </el-form-item>
        <el-form-item label="绩效指标">
          <el-input v-model="editData.performanceIndicator"></el-input>
        </el-form-item>
        <el-form-item label="绩效得分">
          <el-input v-model="editData.performanceScore" type="number"></el-input>
        </el-form-item>
        <el-form-item label="绩效反馈">
          <el-input v-model="editData.performanceFeedback"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="savePerformance">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改/发放工资弹窗 -->
    <el-dialog v-model="dialogVisible2" title="修改/发放工资">
      <el-form :model="editData2" ref="form" label-width="100px">
        <el-form-item label="员工ID" v-show="isVisible">
          <el-input v-model="editData2.employeeId" disabled></el-input>
        </el-form-item>
        <el-form-item label="HR ID" v-show="isVisible">
          <el-input v-model="editData2.hrId" disabled></el-input>
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="editData2.employeeName" disabled></el-input>
        </el-form-item>
        <el-form-item label="基础工资">
          <el-input v-model="editData2.baseSalary"></el-input>
        </el-form-item>
        <el-form-item label="绩效工资">
          <el-input v-model="editData2.bonusSalary"></el-input>
        </el-form-item>
        <el-form-item label="扣款（元）">
            <el-input v-model="editData2.salaryDeduction" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSalary" >提交修改/发放申请</el-button>
          <el-button @click="cancelEdit2">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
      <div>

        <!-- 为指定员工发放绩效记录弹窗 -->
        <el-dialog v-model="addPerformanceByIdDialogVisible" title="选择员工发放绩效记录">
          <el-table :data="employees" border stripe>
            <el-table-column prop="userId" label="员工ID"  />
            <el-table-column prop="fullName" label="员工姓名"  />
            <el-table-column prop="departmentName" label="部门"  />
            <el-table-column prop="positionName" label="职位"  />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" @click="selectEmployee(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>
      </div>

    <!-- 分页器 -->
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
    />
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
    const performanceRecords = ref([]);  // 存储查询到的绩效记录
    const currentPage = ref(1);          // 当前页
    const pageSize = ref(6);            // 每页显示记录数
    const total = ref(0);                // 总记录数
    const dialogVisible = ref(false);    // 控制弹窗的显示与隐藏
    const dialogVisible2 = ref(false);
    const currentUserInfo = sessionStorage.getItem('userInfo');
    const hrId = JSON.parse(currentUserInfo).employeeId;
    // 控制第二个弹窗的显示与隐藏
    const editData = ref({              // 存储要编辑的绩效记录数据
      id: null,
      employeeName: '',
      performanceIndicator: '',
      performanceScore: null,
      performanceFeedback: '',
    });
    const editData2 = ref({             // 存储要编辑的工资数据
      hrId: hrId.value,
      employeeId: null,
      employeeName: '',
      baseSalary: '',
      bonusSalary: null,
      salaryDeduction: null,
      netSalary: null,
    });

    // 获取绩效数据
    const fetchPerformanceData = async (pageNum = 1) => {
      try {
        const response = await axios.get('http://localhost:8080/HR/getAllPerformance', {
          params: {pageNum, pageSize: pageSize.value},
        });
        const {records, total: totalRecords} = response.data.data;
        performanceRecords.value = records;
        total.value = totalRecords;
      } catch (error) {
        console.error("获取绩效数据失败", error);
      }
    };

    // 日期格式化
    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
    };


    // 页码变化时重新加载数据
    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
      fetchPerformanceData(newPage);
    };

    // 编辑绩效记录
    const editPerformance = (record) => {
      editData.value = {...record};
      dialogVisible.value = true;
    };

    // 保存绩效记录
    const savePerformance = async () => {
      try {
        const response = await axios.post('http://localhost:8080/HR/updatePerformance', editData.value);
        if (response.data.code === 200) {
          ElMessage.success('修改成功！');
          fetchPerformanceData(currentPage.value);
          dialogVisible.value = false;
        } else {
          ElMessage.error(`修改失败: ${response.data.message}`);
        }
      } catch (error) {
        console.error("保存失败", error);
        ElMessage.error(`修改失败`);
      }
    };

    // 取消编辑并重置数据
    const cancelEdit = () => {
      dialogVisible.value = false;
      resetEditData();
    };

    // 重置编辑数据
    const resetEditData = () => {
      editData.value = {
        id: null,
        employeeName: '',
        performanceIndicator: '',
        performanceScore: null,
        performanceFeedback: '',
      };
    };

    // 编辑工资记录
    const editSalary = async (record) => {
      resetEditData2();  // 清空数据
      const employeeId = record.employeeId;
      try {
        const response = await axios.get(`http://localhost:8080/HR/getSalaryById?employeeId=${employeeId}`);
        const salaryDeduction = await axios.get(`http://localhost:8080/HR/getAbsenceCount?employeeId=${employeeId}`);
        const data = response.data.data;

        // 将返回的数据填充到编辑数据中
        editData2.value = {
          employeeId: record.employeeId,
          hrId: hrId,
          employeeName: record.employeeName,
          baseSalary: data.baseSalary || 0,
          bonusSalary: data.bonusSalary || 0,
          salaryDeduction: (salaryDeduction.data.data)*100,
        };

        // 打开工资弹窗
        dialogVisible2.value = true;
      } catch (error) {
        console.error("获取工资数据失败", error);
        ElMessage.error("无法加载员工工资数据，请稍后重试！");
      }
    };

    // 重置工资数据
    const resetEditData2 = () => {
      editData2.value = {
        hrId: null,
        employeeId: null,
        employeeName: '',
        baseSalary: '',
        bonusSalary: null,
        salaryDeduction: null,
        netSalary: null,
      };
    };

// 保存工资数据并提交给后端
    const saveSalary = async () => {
      try {
        const response = await axios.post('http://localhost:8080/HR/addApproveSalary', editData2.value);
        if (response.data.code === 200) {
          ElMessage.success('提交成功！');
          dialogVisible2.value = false;
        } else {
          ElMessage.error(`提交失败: ${response.data.message}`);
        }
      } catch (error) {
        console.error("保存工资数据失败", error);
        ElMessage.error(`保存失败`);
      }
    };

    // 取消工资编辑
    const cancelEdit2 = () => {
      dialogVisible2.value = false;
      resetEditData2();
    };

  // 为全部人发放绩效记录（带确认提示）
  const addPerformanceAll = async () => {
    try {
      await ElMessageBox.confirm(
          '确定要为全部员工新增绩效记录吗？此操作不可撤销！',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      );
      // 用户点击确认后执行实际操作
      const response = await axios.post('http://localhost:8080/HR/addPerformanceAll');
      if (response.data.code === 200) {
        ElMessage.success('成功为全部员工新增绩效记录！');
        fetchPerformanceData(currentPage.value); // 刷新列表
      } else {
        ElMessage.error(`发放失败: ${response.data.message}`);
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error("为全部人新增绩效记录失败", error);
        ElMessage.error('操作失败，请稍后重试！');
      }
    }
  };

  const addPerformanceByIdDialogVisible = ref(false);  // 控制弹窗显示
  const employees = ref([]);  // 存储所有员工的基本信息
  const selectedEmployee = ref(null);  // 选择的员工

  const openAddPerformanceByIdDialog = () => {
    addPerformanceByIdDialogVisible.value = true;
    fetchEmployees();  // 打开弹窗时拉取员工数据
  };


  const fetchEmployees = async () => {
    try {
      const response = await axios.get('http://localhost:8080/admin/employees');
      // 过滤掉 employeeId 为空以及 employmentStatus 为 离职 的记录
      employees.value = response.data.data.records.filter(employee =>
          employee.id && employee.employmentStatus !== '离职');
    } catch (error) {
      console.error('获取员工数据失败', error);
      ElMessage.error('无法加载员工数据，请稍后重试');
    }
  };

const selectEmployee = async (employee) => {
  selectedEmployee.value = employee;

  // 显示确认弹窗
  try {
    await ElMessageBox.confirm(
        `确定要为员工 ${employee.fullName} 新增绩效记录吗？此操作不可撤销！`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 用户点击确认后执行实际操作
    const response = await axios.get('http://localhost:8080/HR/addPerformanceById', {
      params: {
        employeeId: employee.id  // 将员工ID作为查询参数传递
      }
    });

    if (response.data.code === 200) {
      ElMessage.success(`成功为 ${employee.fullName} 新增绩效记录`);

      // 获取到新增的绩效记录数据
      //const newPerformanceRecord = response.data.data; // 假设后端返回新增的绩效记录数据
      fetchPerformanceData(currentPage.value);
      // // 将新记录添加到 performanceRecords 中（实时更新表格）
      // performanceRecords.value.push(newPerformanceRecord);
      //
      // // 关闭弹窗
      // addPerformanceByIdDialogVisible.value = false;
      selectedEmployee.value = null;
    } else {
      ElMessage.error(`发放失败: ${response.data.message}`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发放绩效记录失败', error);
      ElMessage.error('操作失败，请稍后重试');
    }
  }
};

// 初始化
    onMounted(() => {
      fetchPerformanceData(currentPage.value);
    });
</script>

<style scoped>
.button-group-vertical {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
